﻿using System;

using UnityEngine;

namespace Assets.XyzCode.Comm
{
    /// <summary>
    /// Cd 计时器
    /// </summary>
    public sealed class CdTimer
    {
        /** 阈值*/
        private readonly float _threshold;

        /** 开始时间 */
        private float _startTime;

        /** 额外时间 */
        private float _extraTime;

        /// <summary>
        /// 类参数构造器
        /// </summary>
        /// <param name="threshold">阈值, 单位 = 秒. 累加时间超过这个值之后, Cd 过热, 就不能再向上累计了</param>
        public CdTimer(float threshold)
        {
            if (threshold <= 0)
            {
                throw new ArgumentOutOfRangeException("threshold <= 0");
            }

            _threshold = threshold;
        }

        /// <summary>
        /// 填满 Cd
        /// </summary>
        /// <returns>this 指针</returns>
        public CdTimer Fill()
        {
            _startTime = GetCurrTime();
            _extraTime = 0;
            return this;
        }

        /// <summary>
        /// 额外多填充一些时间
        /// </summary>
        /// <param name="val">时间值, 单位 = 秒</param>
        public void Extra(float val)
        {
            _extraTime = Mathf.Max(0, val);
        }

        /// <summary>
        /// 是否过热?
        /// </summary>
        /// <returns>true = 过热, 还在冷却中; false = 冷却完毕</returns>
        public bool IsHot()
        {
            return (_startTime + _extraTime + _threshold) > GetCurrTime();
        }

        /// <summary>
        /// 获取当前时间
        /// </summary>
        /// <returns>当前时间</returns>
        private float GetCurrTime() => Time.time;

        /// <summary>
        /// 重置
        /// </summary>
        /// <returns>this 指针</returns>
        public CdTimer Reset()
        {
            _startTime = 0;
            _extraTime = 0;
            return this;
        }
    }
}
